package utils;

import entity.EmailInfo;
import entity.EmailTest;

import java.lang.reflect.Field;

public class ObjectCompareUtils {

    public static String objectCompareContract(Object o1,Object o2) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        Class<?> o1Class = o1.getClass();
        Class<?> o2Class = o2.getClass();
        if (o1Class.equals(o2Class)) {
            System.out.println(o1Class.getName());
            Class c = Class.forName(o1Class.getName());
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields){
                field.setAccessible(true);
                Object f1 = field.get(o1);
                Object f2 = field.get(o2);
                if (!f1.equals(f2)) {
                    stringBuilder.append(field.getName()+": {原:"+f1.toString()+"==>"+"新:"+f2.toString()+"}");
                    stringBuilder.append(",");
                }
            }
        } else {
            throw new Exception("不同的对象，没有可比性");
        }
        String str = stringBuilder.toString();
        if (str.lastIndexOf(",")>0) {
            str = stringBuilder.substring(0,stringBuilder.length()-1);
        }
        str = "{"+str+"}";
        return str;
    }

    public static void main(String[] args) throws Exception {
        EmailInfo e1 = new EmailInfo();
        e1.setId(1L);
        e1.setMessage("1");
        EmailInfo e2 = new EmailInfo();
        e2.setId(2L);
        e2.setMessage("12");
        EmailTest o3 = new EmailTest();
        objectCompareContract(e1,e2);
        //objectCompareContract(e1,o3);
    }
}
